package com.cosmosource.core.config;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author cosmo
 * @date
 */
@Slf4j
public class PortConfig extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        try {
            List<MBeanServer> serverList = MBeanServerFactory
                    .findMBeanServer(null);
            for (MBeanServer server : serverList) {
                Set<ObjectName> names = new HashSet<>(server.queryNames(new ObjectName(
                        "Catalina:type=Connector,*"), null));
                for (ObjectName oName : names) {
                    String pValue = (String) server.getAttribute(oName,
                            "protocol");
                    if (StringUtils.equals("HTTP/1.1", pValue)) {
                        Object port = server.getAttribute(oName, "port");
                        return (port == null) ? "" : port.toString();
                    }
                }
            }
        } catch (Exception e) {
        }
        return StringUtils.EMPTY;
    }

}
